import axios from './index'
import { getLocalData, setLocalData } from '../utils'

export type ResponseData = {
  code: number;
}

export type LoginType = 'phone' | 'email' | 'refresh'
export type LoginParams = {
  phone?: string;
  password?: string;
  email?: string;
}

export const MyRequest = (key: 'get' | 'post', url: string, params?: {}) => {
  return axios[key]<ResponseData>('', url, params)
}

export const login = async (type: LoginType, params?: LoginParams) => {
  if (type === 'phone') {
    return MyRequest('get', '/login/cellphone', { params })
  } else if (type === 'email') {
    return MyRequest('get', '/login', { params })
  } else if (type === 'refresh') {
    return MyRequest('get', '/login/refresh')
  }
}


export const handleLogin = (type: LoginType, params: LoginParams) => {

  login('phone', params).then(res => {
    if (res?.data.code === 200) {
      setLocalData('ck', res.data)
      type === 'refresh' ? alert('刷新登入状态成功') : alert('登入成功')
      window.location.reload()
    } else {
      alert('接口调用失败')
    }
  })
}

export const getProfile = async () => {
  let data = null
  const isHaveProfile = getLocalData('profile')
  if (!isHaveProfile) {
    data = await axios.get('/user/account')
    setLocalData('profile', data)
  } else {
    data = isHaveProfile
  }
  return data
}

export const getPersonalFM = async () => {
  let data = null
  const isHaveFm = getLocalData('fm')
  if (!isHaveFm) {
    data = await axios.get('/personal_fm')
    setLocalData('fm', data)
  } else {
    data = isHaveFm
  }
  return data
}